﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WanderingAI : MonoBehaviour
{
    //速度
    public float speed = 3.0f;
    //由速度设置调整的基本速度
    public const float baseSpeed = 3.0f;
    //做出反应的距离
    public float obstacleRange = 5.0f;
    //判断敌人是否存活
    private bool _alive;

    [SerializeField] private GameObject fireballPrefab;
    private GameObject _fireball;

    void Awake()
    {
        Messenger<float>.AddListener(GameEvent.SPEED_CHANGED, OnSpeedChanged);
    }

	// Use this for initialization
	void Start ()
	{
	    _alive = true;
	}
	
	// Update is called once per frame
	void Update ()
	{
	    if (_alive)
	    {
	        transform.Translate(0, 0, speed * Time.deltaTime);
	        //与角色相同位置的射线，并且方向相同
	        Ray ray = new Ray(transform.position, transform.forward);
	        RaycastHit hit;
	        if (Physics.SphereCast(ray, 0.75f, out hit))
	        {
	            GameObject hitObject = hit.transform.gameObject;
	            if (hitObject.GetComponent<PlayerCharacter>())
	            {
	                if (_fireball == null)
	                {
	                    _fireball = Instantiate(fireballPrefab) as GameObject;
                        //把火球放置在敌人面前并指向同一方向
	                    _fireball.transform.position = transform.TransformPoint(Vector3.forward * 1.5f);
	                    _fireball.transform.rotation = transform.rotation;
	                }
	            }
	            else if (hit.distance < obstacleRange)
	            {
	                //转向一个随机的方向
	                float angle = Random.Range(-110, 110);
	                transform.Rotate(0, angle, 0);
	            }
	        }
        }
	}

    //允许外部代码影响alive值
    public void SetAlive(bool alive)
    {
        _alive = alive;
    }

    void OnDestroy()
    {
        Messenger<float>.RemoveListener(GameEvent.SPEED_CHANGED, OnSpeedChanged);
    }

    //声明该方法,用于侦听事件SPEED_CHANGED
    private void OnSpeedChanged(float value)
    {
        speed = baseSpeed * value;
    }
}
